package com.mypage.view.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.mobile.AppConfig;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.widget.listview.CloudCCListView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.adapter.NDefauleChageListAdapter;
import com.mypage.adapter.NewHistoryCheckInAdapter;
import com.mypage.bean.CheckInBean;
import com.mypage.bean.CreateGoupPersonBean;
import com.mypage.model.NewcontactLixnxi;
import com.mypage.utils.MyListView;
import com.mypage.utils.RecordSQLiteOpenHelper;
import com.mypage.utils.UtilsShowDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GongniuCheckinHistoryActivity extends BaseActivity implements CloudCCListView.OnRefreshOrLoadMoreListener {
    public List<CreateGoupPersonBean.Custom> mList;
    public List<CheckInBean.Locations> mQList;
    public NewHistoryCheckInAdapter mAdapter;
    @Bind(R.id.layoutShow)
    LinearLayout layoutShow;
    @Bind(R.id.frameLayoutBtn)
    FrameLayout frameLayoutBtn;
    private String recordId, layoutId, relatedlistId;
    public NDefauleChageListAdapter mDefaultAdapter;
    public static GongniuCheckinHistoryActivity instance = null;
    @Bind(R.id.searchData)
    TextView searchData;
    @Bind(R.id.searchDataButtonLine)
    View searchDataButtonLine;
    @Bind(R.id.noContent)
    TextView noContent;
    @Bind(R.id.noContentButtonLine)
    View noContentButtonLine;
    @Bind(R.id.textUser)
    TextView textUser;
    private UtilsShowDialog showDialog;
    @Bind(R.id.btnImgBack)
    ImageView btnImgBack;
    @Bind(R.id.etSearchContent)
    ClearEditText etSearchContent;
    @Bind(R.id.imgClean)
    ImageView imgClean;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
    }

    @Bind(R.id.listCustom)
    CloudCCListView listCustom;
    @Bind(R.id.lianxineme)
    TextView lianxineme;
    @Bind(R.id.listView)
    MyListView listView;
    @Bind(R.id.tv_clear)
    TextView tvClear;
    //    @Bind(R.id.linearLayout)
//    LinearLayout linearLayout;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private BaseAdapter adapter;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_new_contact_lianxi);
        ButterKnife.bind(this);
        instance = this;
        showDialog = new UtilsShowDialog(this);
        listCustom.setOnRefreshOrLoadMoreListener(this);
        initdata();
        mHttpQueryData();
        //        getDataHttp();//默认访问用户列表
        textChange();
        initView();
        initListener();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_gongniu_checkin_history;
    }

    private void initdata() {
        Intent intent = getIntent();
        recordId = intent.getStringExtra("recordId");
        layoutId = intent.getStringExtra("layoutId");
        relatedlistId = intent.getStringExtra("relatedlistId");
    }

    //监听输入框的变化
    public void textChange() {
        // 搜索框的文本变化实时监听
        etSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                String mContent = etSearchContent.getText().toString();
                noContent.setVisibility(View.GONE);
                noContentButtonLine.setVisibility(View.GONE);
//                mHttpQueryData();
                if ("".equals(mContent)) {
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
//                    imgClean.setVisibility(View.GONE);
                } else {
//                    imgClean.setVisibility(View.VISIBLE);
                    searchData.setVisibility(View.VISIBLE);
                    searchDataButtonLine.setVisibility(View.VISIBLE);
                    searchData.setText("搜索”" + mContent + "“");

                }


            }

            @Override
            public void afterTextChanged(Editable s) {

//                String tempName = etSearchContent.getText().toString();
//                // 根据tempName去模糊查询数据库中有没有数据
//                queryData(tempName);

            }
        });
    }

    public void initView() {
        etSearchContent.setHint(R.string.input_mingcheng);
        lianxineme.setText(R.string.tong_shis);
        textUser.setText(R.string.kaoqinlishi);
    }

    public void initListener() {
        etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mAdapter.notifyDataSetChanged();
                    mQList.clear();
                    setKeyBoard();
                    // TODO: 2017/5/11
                    showDialog.onShowLoadingDialog("正在加载...");
                    mHttpQueryData();
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
                }
                return false;
            }
        });
//        listCustom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//            }
//        });
        //搜索
        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                mHttpQueryData();
                listCustom.setVisibility(View.VISIBLE);
//                linearLayout.setVisibility(View.INVISIBLE);
                Toast.makeText(GongniuCheckinHistoryActivity.this, etSearchContent.getText().toString(), Toast.LENGTH_SHORT)
                        .show();
                //                //删除数据库的历史记录
                //                deleteData();
                //                queryData("");
            }
        });
        //搜索结果的listiew
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                TextView textView = (TextView) view
                        .findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                etSearchContent.setText(name);
                //                Toast.makeText(NewInputNameActivity.this, name + " 来了啊", Toast.LENGTH_SHORT)
                //                        .show();
                // TODO 获取到item上面的文字，根据该关键字跳转到另一个页面查询，由你自己去实现
            }
        });
        // 第一次进入查询所有的历史记录
        queryData("");
        frameLayoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isAsk = true ;
                frameLayoutBtn.setVisibility(View.GONE);
                layoutShow.setVisibility(View.VISIBLE);
                listCustom.setVisibility(View.GONE);
            }
        });
    }

    @OnClick(R.id.searchData)
    public void searchData() {
        showDialog.onShowLoadingDialog(getString(R.string.nowjiazai));
        mHttpQueryData();
        searchData.setVisibility(View.GONE);
        searchDataButtonLine.setVisibility(View.GONE);
        if (mQList.size() == 0) {
            searchData.setVisibility(View.GONE);
            searchDataButtonLine.setVisibility(View.GONE);
            noContent.setVisibility(View.VISIBLE);
            noContentButtonLine.setVisibility(View.VISIBLE);
            noContent.setText(getString(R.string.pipeijieguo) + etSearchContent.getText().toString() + getString(R.string.jieguopipie));
        }
        //    Toast.makeText(this,"sssssssssss",3).show();
    }

    @OnClick({R.id.btnImgBack, R.id.imgClean})
    public void setOnClick(ImageView v) {
        switch (v.getId()) {
            case R.id.imgClean:
                etSearchContent.setText("");
                break;
            case R.id.btnImgBack:
                if (isAsk){
                    isAsk = false;
                    frameLayoutBtn.setVisibility(View.VISIBLE);
                    layoutShow.setVisibility(View.GONE);
                    listCustom.setVisibility(View.VISIBLE);
                }else {
                    finish();
                }

                break;


        }
    }


    /**
     * 点击按钮隐藏键盘
     */
    public void setKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getApplicationContext().
                getSystemService(GongniuCheckinHistoryActivity.this.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(etSearchContent.getWindowToken(), 0); //隐藏
    }


    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%"
                        + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"}, new int[]{android.R.id.text1},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?",
                new String[]{tempName});
        // 判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }


    public void saveData() {
        // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
        boolean hasData = hasData(etSearchContent.getText()
                .toString().trim());
        if (!hasData) {
            insertData(etSearchContent.getText().toString()
                    .trim());
            queryData("");
        }
    }

    private List<NewcontactLixnxi.Custom> newQlist;

    public void mHttpQueryData() {
        String b = RunTimeManager.getInstance().getServerBinding();
        String u = UrlManager.getInterfaceUrl();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "pageQuery");
        params.addBodyParameter("objectApiName", "kqxx");

        String express = "ownerid="+"'"+RunTimeManager.getInstance().getUserId()+"'" +"order by kqrq desc";


        params.addBodyParameter("expressions", "ownerid="+"'"+RunTimeManager.getInstance().getUserId()+"'" +"order by kqrq desc");

        params.addBodyParameter("pageNUM", String.valueOf(page));
        params.addBodyParameter("pageSize", "5");

        com.litesuits.android.log.Log.d("request历史接口url---", u + "?binding=" + b + "&serviceName=pageQuery&objectApiName=kqxx&expressions="
                +express+"&pageNUM="+String.valueOf(page)+"&pageSize=5");


        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Log.d("request查询客户Fail", arg1);
                if (isFromRefresh()) {
                    listCustom.refreshComplete();
                    listCustom.handlerLoadMoreFinish(true, false);
                } else {
                    listCustom.handlerLoadMoreError(1002, arg1);
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
                listCustom.refreshComplete();
//                listCustom.handlerLoadMoreFinish(true, false);
                Log.d("request查询客户Success", arg0.result.toString());
                CheckInBean mCustom = new Gson().fromJson(arg0.result.toString(), CheckInBean.class);
                mQList = mCustom.data;
                if (null == mQList) {
                    noContent.setVisibility(View.GONE);
                    listCustom.setVisibility(View.GONE);

                    return;
                } else {
                    listCustom.setVisibility(View.VISIBLE);

                }
                if (0 < mQList.size() && mQList.size() < 13) {
                    if (isFromRefresh()) {
                        listCustom.refreshComplete();
                        listCustom.handlerLoadMoreFinish(true, true);
                    } else {
                        listCustom.refreshComplete();
                        listCustom.handlerLoadMoreFinish(false, false);// 不是来自刷新 是来自
//                    listCustom.handlerLoadMoreError(1002, "加载失败");
                    }
                } else {
                    onRequestFinish(ListUtils.isEmpty(mQList));
                }
                if (mQList.size() >= 0) {
//                    searchData.setVisibility(View.GONE);
//                    searchDataButtonLine.setVisibility(View.GONE);
//                    noContent.setVisibility(View.VISIBLE);
//                    noContentButtonLine.setVisibility(View.VISIBLE);
//                    noContent.setText(getString(R.string.pipeijieguo) + etSearchContent.getText().toString() + getString(R.string.jieguopipie));
//                    showDialog.onDismissLoadingDialog();
//                    listCustom.setVisibility(View.GONE);
//                    return;
//                }else{
                    showDialog.onDismissLoadingDialog();
                    listCustom.setVisibility(View.VISIBLE);
                }

                if (mAdapter == null) {
                    mAdapter = new NewHistoryCheckInAdapter(mQList, GongniuCheckinHistoryActivity.this, etSearchContent.getText().toString());
                    listCustom.setAdapter(mAdapter);
                    showDialog.onDismissLoadingDialog();
                } else {
                    if (!isFromRefresh()) {
                        Log.d("zoudaolenali", "開始匹配+BeauListEvent");
                        mAdapter.addData(mQList);
                    } else {
                        mAdapter = new NewHistoryCheckInAdapter(mQList, GongniuCheckinHistoryActivity.this, etSearchContent.getText().toString());
                        listCustom.setAdapter(mAdapter);
                        showDialog.onDismissLoadingDialog();
                    }
                }

            }
        });


    }

    public String getDatea() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(d);
//        return "('" + sdf.format(d) + "','yyyy-MM-dd')";
    }

    @Override
    public void onRefresh(PtrFrameLayout frame) {
        page = 1;
        mHttpQueryData();
//        listCustom.refreshComplete();
//        listCustom.handlerLoadMoreFinish(true, false);

    }

    @Override
    public void onLoadMore(LoadMoreContainer frame) {
        page++;
        mHttpQueryData();

    }

    private void onRequestFinish(boolean dataIsEmpty) {
        if (isFromRefresh()) {// 第一次加载 并且数据出现空的话 就显示 空
            listCustom.refreshComplete();
            listCustom.handlerLoadMoreFinish(dataIsEmpty, !dataIsEmpty);// 第一次加载
            listCustom.isfirst();
        } else {
            listCustom.refreshComplete();
            listCustom.handlerLoadMoreFinish(false, !dataIsEmpty);// 不是来自刷新 是来自
            // 上啦加载更多
            // 这样的话
        }
    }

    protected boolean isFromRefresh() {
        return page <= AppConfig.DEFAULTPAGE;
    }

    /**
     * 点击按钮隐藏键盘
     */
    public String getDateTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(d);
    }
    public boolean isAsk = false ;


}
